/*
 * @Author: liangbo
 * @Date: 2020-05-07 15:30:55
 * @LastEditTime: 2020-06-05 17:43:13
 * @LastEditors: Please set LastEditors
 * @Description: 数据库配置及模型导入
 * @FilePath: \tuyibo\servers\models\index.js
 */

const cfg = require('../config')
const dbLog = require('../config/log4js').dbLog
const { Sequelize } = require('sequelize');

const sequelize = new Sequelize(cfg.mysql.database, cfg.mysql.username, cfg.mysql.password, {
  host: cfg.mysql.host,
  port: cfg.mysql.port || 3306,
  dialect: 'mysql',
  logging: function(msg){ dbLog.info(msg) }
});

sequelize.authenticate().then(async function () {
  console.log('Connection has been established successfully.');
  await models.tag.getAllTag().then(re=>{
    console.log('Redis has load all tags')
  }).catch(err=>{
    console.log('Redis load all tags error')
  })
  await models.category.setAllInRedis().then(re=>{
    console.log('Redis has load all category')
  }).catch(err=>{
    console.log('Redis load all category error')
  })
}).catch(function (err) {
  console.log('Unable to connect to the database:', err);
});

const models = {
  sequelize: sequelize,
  banner: sequelize.import('Banner', require('./m_banner')),
  topic: sequelize.import('Topic', require('./m_topics')),
  images: sequelize.import('ImagesBaseModel', require('./m_images')),
  search_bar: sequelize.import('searchBar', require('./m_search_bar')),
  special_topic: sequelize.import('specialTopic', require('./m_special_topic')),
  recommend_category: sequelize.import('recommendCategory', require('./m_recommend_category')),
  user: sequelize.import('./user', require('./user/m_user')),
  user_favorites: sequelize.import('./user', require('./user/m_user_favorior')),
  tag: sequelize.import('Tag', require('./m_tags')),
  topic_relation: sequelize.import('topicRelation', require('./m_topic_relation')),
  tagImage:sequelize.import('tagImage',require('./m_tag_image_map')),
  tagIcon:sequelize.import('tagIcon',require('./m_tag_icon_map')),
  group:sequelize.import('group',require('./m_group')),
  category:sequelize.import('category',require('./m_category')),
  admin:sequelize.import('./admin',require('./admin/m_admin')),
  userDownloads:sequelize.import('userDownloads',require('./m_user_downloads')),
  userFavorites:sequelize.import('userFavorites',require('./m_user_favorites')),
  userBehavior:sequelize.import('userBehavior',require('./m_user_behavior')),
  icons:sequelize.import('icons',require('./m_icons')),
}


//models.tagImage.belongsTo(models.images, {foreignKey: 'image_id'})

module.exports = models


